<template>
  <div class="roles_container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="addRoleFormVisible=true ">添加角色</el-button>
      <el-table :data="roleList" style="width: 100%" border stripe>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-row
              v-for="(item, index) in props.row.children"
              :key="item.id"
              :class="['bottom_border',index ==0 ? 'top_border': '', 'vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(props.row,item.id)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二三级权限渲染 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, index) in item.children"
                  :key="item2.id"
                  :class="['bottom_border',index+1 === item.children.length ? 'bottom_border_cancel': '','vcenter']"
                >
                  <!-- 二级权限的渲染 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(props.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级权限的渲染 -->
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      class="tag_threeDegree"
                      closable
                      @close="removeRightById(props.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" width="70" label="序号"></el-table-column>
        <el-table-column prop="roleName" label="名称"></el-table-column>
        <el-table-column prop="roleDesc" label="描述"></el-table-column>
        <el-table-column label="操作" width="350">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit"
              type="primary"
              size="mini"
              @click="editRole(scope.row)"
            >编辑</el-button>

            <el-button
              icon="el-icon-delete"
              type="danger"
              size="mini"
              @click="deleteRole(scope.row)"
            >删除</el-button>
            <el-button
              icon="el-icon-setting"
              type="warniing"
              size="mini"
              @click="showRightForm(scope.row)"
            >设置权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框弹出 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleFormVisible"
      width="30%"
      :show-close="false"
      :modal="true"
      :close-on-click-modal="false"
    >
      <el-form :model="newRole" ref="newRoleFormRef">
        <el-form-item label="角色名" label-width="20%" props="roleName">
          <el-input v-model="newRole.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" label-width="20%" prop="roleDescribe">
          <el-input v-model="newRole.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRoleCancel">取 消</el-button>
        <el-button type="primary" @click="admitNewRole">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 权限分配对话框弹出 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightFormVisible"
      width="30%"
      :show-close="false"
      :modal="true"
      :close-on-click-modal="false"
    >
      <el-tree
        :data="rightList"
        :props="treeData"
        show-checkbox
        :default-checked-keys="defKeys"
        node-key="id"
        ref="treeRef"
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setRightCancel">取 消</el-button>
        <el-button type="primary" @click="submitRight">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],
      rightList: [],
      // 此用户拥有的权限
      defKeys: [],
      addRoleFormVisible: false,
      setRightFormVisible: false,
      newRole: {
        roleName: '',
        roleDesc: ''
      },
      editId: '',
      roleId: '',
      treeData: { label: 'authName', children: 'children', id: 'id' }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取管理者权限列表
    getRoleList() {
      this.$http.get(`roles`).then(res => {
        if (res.data.meta.status != 200) {
          // this.$message.closeAll()
          this.$message.error('获取数据失败')
        }
        // console.log(res.data.data)
        this.roleList = res.data.data
      })
    },
    // 取消添加角色
    addRoleCancel() {
      this.addRoleFormVisible = false
      this.$refs.newRoleFormRef.resetFields()
    },
    // 添加角色，同时附带删除角色
    admitNewRole() {
      if (this.newRole.roleName == '') {
        return this.$message.error('角色名不能为空')
      } else {
        this.$http.post('roles', this.newRole).then(res => {
          if (res.data.meta.status != 201) {
            this.$message.error('抱歉，添加失败')
          } else {
            this.$message.success('添加成功')
            this.$refs.newRoleFormRef.resetFields()
          }
        })
      }

      if (this.editId) {
        //删除此用户
        this.$http.delete(`roles/${this.editId}`).then(res => {
          if (res.data.meta.status != 200) {
            this.$message.error('错误，请暂停使用并联系维护人员')
          }
          this.$message.success('成功')
        })
        this.editId = ''
      }
      this.$router.go(0)
    },
    // 编辑操作，
    editRole(oldRole) {
      // console.log(roleId)
      Object.keys(this.newRole).forEach(key => {
        this.newRole[key] = oldRole[key]
      })
      this.addRoleFormVisible = true
      this.editId = oldRole.id
    },
    // 删除操作
    deleteRole(roleData) {
      this.$confirm('此操作将永久删除此角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http.delete(`roles/${roleData.id}`).then(res => {
            if (res.data.meta.status != 201) {
              this.$message.closeAll()
              this.$message.error('删除失败')
            }
            this.$message.success('删除成功')
          })
          this.$router.go(0)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 根据id删除权限
    removeRightById(role, rightId) {
      // 先确认是否真的删除
      this.$confirm('此操作将删除此权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log('确认删除了')
          this.$http.delete(`roles/${role.id}/rights/${rightId}`).then(res => {
            if (res.data.meta.status != 200) {
              console.log(res.data)

              this.$message.error('删除失败')
            } else {
              this.$message.success('删除成功')
              // 为什么这样也可以删除？
              role.children = res.data.data
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 分配权限对话框展示
    showRightForm(data) {
      this.roleId = data.id
      // console.log(data)
      // 获取所有的叶子节点/三级节点
      this.getLeafKeys(data, this.defKeys)
      this.getRightList()
      this.setRightFormVisible = true
    },
    // 获取权限列表
    async getRightList() {
      const { data: res } = await this.$http.get('rights/tree')
      // console.log(res)
      if (res.meta.status != 200) {
        this.$message.closeAll()
        return this.$message.error('获取数据失败')
      }
      this.rightList = res.data
      // console.log(this.rightList)
    },
    // 分配好的权限提交
    submitRight() {
      // console.log(...this.$refs.treeRef.getCheckedKeys())
      const keys = [
        //使用组件自带的方法获取目前选中或半选中的权限id
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      this.$http
        .post(`roles/${this.roleId}/rights`, { rids: idStr })
        .then(res => {
          console.log(res.data)
          if (res.data.meta.status != 200) {
            this.$message.closeAll()
            return this.$message.error('请求失败')
          }
          this.$message.success('权限分配成功'), this.$router.go(0)
        })
    },
    // 取消分配的权限操作
    setRightCancel() {
      this.setRightFormVisible = false
      this.defKeys = []
    },
    // 通过递归获取所有三级权限id
    getLeafKeys(node, arr) {
      // console.log(node)
      // 如果没有children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
      // console.log(arr)
    }
  }
}
</script>

<style lang="less" scoped>
.roles_container {
  .el-card {
    margin-top: 20px;
    .el-table {
      margin-top: 20px;
      // height: 641px;
      .bottom_border {
        margin-bottom: 15px;
        border-bottom: 1px solid #ccc;
        padding: 0 0 15px 0;
      }
      .top_border {
        border-top: 1px solid #ccc;
        padding-top: 15px;
      }
      .bottom_border_cancel {
        border-bottom: none;
        padding-bottom: 0;
      }
      .tag_threeDegree {
        // margin-top: 10px;
        margin-right: 4px;
      }
    }
  }

  .vcenter {
    display: flex;
    align-items: center;
  }
}
</style>